package com.hyt.it.ogt.opertaion.track.aspect.base;

import com.hyt.it.ogt.opertaion.track.util.AspectUtils;
import com.hyt.it.ogt.opertaion.track.util.NonWebRequestAttributes;
import com.hyt.it.ogt.opertaion.track.util.WebRequestUtil;
import org.aspectj.lang.JoinPoint;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.naming.OperationNotSupportedException;
import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.hyt.it.ogt.opertaion.track.constants.OperationTrackConstants.HEADER_TOKEN;

/**
 * @author 朱振宇
 * @since 2022-11-24
 */
public class BaseServiceAspect {

    protected boolean saveByJoinPoint(final JoinPoint joinPoint, Annotation annotation) throws Exception {
        List<Map<String, Object>> fieldValMaps;
        if(!(fieldValMaps = AspectUtils.getFieldValMap(joinPoint.getArgs(), joinPoint, annotation)).isEmpty()) {
            try {
                execute(fieldValMaps, annotation);
                return true;
            } catch (Exception e) {
                throw e;
            }
        }
        return false;
    }

    protected boolean saveByJsonResult(Object jsonResult, JoinPoint joinPoint, Annotation annotation) throws Exception {
        List<Map<String, Object>> fieldValMaps;
        if(Objects.nonNull(jsonResult)) {
            if((fieldValMaps = AspectUtils.getFieldValMap(new Object[]{jsonResult}, joinPoint, annotation)) != null) {
                execute(fieldValMaps, annotation);
                return true;
            }
        }
        return false;
    }

    protected void execute(List<Map<String, Object>> fieldValMaps, Annotation annotation) throws Exception {
        throw new OperationNotSupportedException();
    }

    protected String getUserId() {
        String userId = WebRequestUtil.getAuthUser();
        return userId==null || userId.length()>32?null:userId;
    }

    protected String getToken() {
        RequestAttributes requestAttributes = WebRequestUtil.getRequestAttributesSafely();
        if(!(requestAttributes instanceof NonWebRequestAttributes)) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            return request.getHeader(HEADER_TOKEN);
        }
        return null;
    }
}
